package org.wisdom.ac.apis.assembler;

import cn.hutool.core.bean.BeanUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.wisdom.ac.domain.user.entity.AcUser;
import org.wisdom.ac.domain.user.entity.AcUserRole;
import org.wisdom.ac.domain.role.repository.RoleRepository;
import org.wisdom.ac.dto.UserDto;
import org.wisdom.exception.BusinessException;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 系统用户组装器
 *
 * @author 张智研
 * @date 2022/05/23 13:59
 **/
@RequiredArgsConstructor
@Component
public class UserAssembler {

    private final RoleRepository roleRepository;

    /**
     * dto转换为实体
     *
     * @author 张智研
     * @date 2022/05/27 21:09
     * @param userDto
     *            用户信息
     * @return org.wisdom.ac.domain.entity.AcApp
     */
    public AcUser userDtoToEntity(UserDto userDto) {
        AcUser user = BeanUtil.copyProperties(userDto, AcUser.class, "userRoles");
        String[] userRoleIds = userDto.getUserRoles();
        List<AcUserRole> userRoleList = new ArrayList<>();
        for (String userRoleId : userRoleIds) {
            boolean isExists = this.roleRepository.existsById(userRoleId);
            if (!isExists) {
                throw new BusinessException("角色{" + userRoleId + "}不存在!");
            }
            AcUserRole userRole = new AcUserRole();
            userRole.setRoleId(userRoleId);
            userRoleList.add(userRole);
        }
        user.setUserRoles(userRoleList);
        return user;
    }

    /**
     * 实体转换为dto
     * 
     * @author 张智研
     * @date 2022/05/31 13:05
     * @param user
     *            用户
     * @return org.wisdom.ac.dto.UserDto
     */
    public UserDto userEntityToDto(AcUser user) {
        UserDto userDto = BeanUtil.copyProperties(user, UserDto.class, "password", "userRoles");
        List<AcUserRole> userRoleList = user.getUserRoles();
        String[] userRoles = new String[userRoleList.size()];
        int n = 0;
        for (AcUserRole userRole : userRoleList) {
            userRoles[n++] = userRole.getRoleId();
        }
        userDto.setUserRoles(userRoles);
        return userDto;
    }

    /**
     * entity列表转换为dto列表
     *
     * @author 张智研
     * @date 2022/05/23 09:55
     * @param userList
     *            用户列表
     * @return java.util.List<org.wisdom.ab.dto.UserDto>
     */
    public List<UserDto> userListEntityToDto(List<AcUser> userList) {
        return userList.stream().map(this::userEntityToDto).collect(Collectors.toList());
    }
}
